import { Button, Card, Pagination, Space, Table, TableProps, Tag } from "antd";
import React, { useEffect, useRef, useState } from "react";
import SearchForm, { searchParam } from "../components/SearchForm";
import { ContarctData, getContractListService } from "@/services/api/finance";
import { useRequest } from "ahooks";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { StateType } from "@/store";
import { reset } from "@/store/finance/contractSlice";

const initPage = { pageNo: 1, pageSize: 10 };
const initSearch = {
  contractNo: "",
  contact: "",
  tel: "",
};

/**
 * 合同管理页面：
 * 1. 常规的表格数据展示+分页+查询
 * 2. 当从合同详情页返回当前页面时，实现数据缓存功能
 */
const Contract: React.FC = (props) => {
  const nav = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();

  const {list, total, page, search} = useSelector((state: StateType) => state.contractSlice);
  
  const [defaultSearch, setDefaultSearch] = useState(initSearch);
  const searchRef = useRef<searchParam>(initSearch);

  /** 
   * 如果当前为合同详情页跳转过来，并且列表数据不为空时，使用缓存数据
   * 否则，请求服务端数据
   */
  useEffect(() => {
    console.log(location, list);
    if (location.state?.enableCache && list.length > 0) {
      setDefaultSearch(search);
    } else {
      run({ ...initPage, ...searchRef.current });
    }
  }, []);

  /** 数据请求Hooks */
  const { run, loading } = useRequest(getContractListService, {
    manual: true,
    onSuccess(data, params) {
      const {list, total, pageNo, pageSize} = data;
      dispatch(
        reset({
          list,
          total,
          page: {pageNo, pageSize},
          search: searchRef.current,
        })
      );
    },
  });

  /** 处理Page行为 */
  function handlePageChange(pageNo: number, pageSize: number): void {
    run({ pageNo, pageSize, ...searchRef.current });
  }

  /** 处理查询数据 */
  function handleSearch() {
    run({ ...initPage, ...searchRef.current });
  }

  /** 处理重置数据 */
  function handleResetData() {
    run({ ...initPage, ...initSearch });
  }

  /** 处理跳转合同详情页 */
  function handleToDetails(contractNo: string) {
    dispatch(
      reset({
        page,
        total,
        search: searchRef.current,
        list,
      })
    );
    nav(`/finance/surrender?contractNo=${contractNo}`);
  }

  const columns: TableProps<ContarctData>["columns"] = [
    {
      title: "No.",
      key: "index",
      render(value, record, index) {
        return index + 1;
      },
    },
    {
      title: "合同编号",
      key: "contractNo",
      dataIndex: "contractNo",
    },
    {
      title: "合同类型",
      key: "type",
      dataIndex: "type",
    },
    {
      title: "合同名称",
      key: "name",
      dataIndex: "name",
    },
    {
      title: "开始日期",
      key: "startDate",
      dataIndex: "startDate",
    },
    {
      title: "结束日期",
      key: "endDate",
      dataIndex: "endDate",
    },
    {
      title: "甲方",
      key: "partyA",
      dataIndex: "partyA",
    },
    {
      title: "乙方",
      key: "partyB",
      dataIndex: "partyB",
    },
    {
      title: "审批状态",
      key: "status",
      dataIndex: "status",
      render(value, record, index) {
        if (value === "1") return <Tag color="green">审批通过</Tag>;
        if (value === "2") return <Tag>未审批</Tag>;
        if (value === "3") return <Tag color="red">审批结束</Tag>;
      },
    },
    {
      title: "操作",
      key: "operate",
      render(value, record, index) {
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => {
              handleToDetails(record.contractNo);
            }}
          >
            合同详情
          </Button>
        );
      },
    },
  ];

  return (
    <div>
      <Space className="fx" direction="vertical" size="large">
        <Card>
          <SearchForm
            ref={searchRef}
            searchData={handleSearch}
            resetData={handleResetData}
            initSearch={defaultSearch}
          />
        </Card>
        <Card>
          <Table
            columns={columns}
            dataSource={list}
            rowKey={(record) => record.contractNo}
            loading={loading}
            pagination={false}
          />
          <Pagination
            style={{ marginTop: "12px" }}
            showQuickJumper
            align="end"
            total={total}
            current={page.pageNo}
            pageSize={page.pageSize}
            showTotal={(total) => `共 ${total} 条`}
            onChange={handlePageChange}
          />
        </Card>
      </Space>
    </div>
  );
};

export default Contract;
